import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, Switch } from "@tarojs/components";
import { useReactive, useUpdateEffect } from "ahooks";

import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import ByText from "@/components/ui/ByText";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import PopupStandardContent from "./components/PopupStandardContent";

import useForm from "@/hooks/useForm";
import useList from "@/hooks/useList";
import ApiInspection from "@/api/inspection";

import type {
  InspectionStandardContent,
  InspectionStandardTemplate,
} from "@/types/Inspection";

// 获取统计数据
function getStatistic(list: InspectionStandardContent[]) {
  return list.reduce(
    (obj, { picList, options }) => {
      const option = options.find((e) => e.isCheck);

      if (option) {
        if (option.isQualified) {
          obj.pass += 1;
        } else {
          obj.unpass += 1;
        }
      } else {
        obj.remain += 1;
      }

      obj.pics = [...obj.pics, ...(picList || [])];
      return obj;
    },
    {
      pass: 0,
      unpass: 0,
      remain: 0,
      pics: [] as string[],
    }
  );
}

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const { list } = useList<InspectionStandardTemplate>(
    ApiInspection.inspectionStandardTemplate
  );

  const [quesList, setQuesList] = useState<InspectionStandardTemplate[]>([]);

  useUpdateEffect(() => {
    setQuesList(list);
  }, [list]);

  const { loading, model, setModel, submit } = useForm<{
    intentCustomerId: number;
    isCanSee: boolean;
    isPicture: boolean;
    longitude: string;
    latitude: string;
    quesList: any[];
  }>(ApiInspection.inspectionStandardCreate, {
    defaultModel: { intentCustomerId },
    onSuccess() {
      Taro.showToast({ title: "提交成功！" });
      setTimeout(() => {
        Taro.navigateBack({ delta: 1 });
      }, 1500);
    },
  });

  const formModel = useReactive({
    isCanSee: false,
    isPicture: false,
    longitude: "",
    latitude: "",
  });

  useUpdateEffect(() => {
    submit();
  }, [model]);

  // 提交事件
  const beforeSubmit = () => {
    const newList = quesList.map((e) => ({
      ...e,
      remark: "",
      quesNaireTempId: e.quesNaireId,
      questionTemplate: e.quesNaireContent.map((e) => {
        e.quesTempID = e.quesNaireId;
        e.picList = e.picList || [];
        e.quesRemark = e.quesRemark || "";

        e.options = e.options.map((option) => {
          option.optionsTempId = option.optionsId;
          // option.
          return option;
        });
        return e;
      }),
    }));
    setModel({ ...formModel, quesList: newList });
  };

  const [index, setIndex] = useState<number>(-1);
  const handleChange = (newContent) => {
    // 不要求刷新UI
    quesList[index] = {
      ...quesList[index],
      quesNaireContent: newContent,
    };
    setIndex(-1);
  };

  const statistic = list?.map((e) => getStatistic(e.quesNaireContent));

  // 编辑数据
  const modifyData = quesList[index];

  const showPopup = index > -1;

  return (
    <>
      <Page
        slotFooter={
          <ByButton
            size="large"
            className="w-2/3"
            loading={loading}
            onClick={beforeSubmit}
          >
            保存
          </ByButton>
        }
      >
        <ByCellGroup className="m-3">
          <ByCell label="业主可见" align="right">
            <Switch
              checked={formModel.isCanSee}
              onClick={() => (formModel.isCanSee = !model.isCanSee)}
            />
          </ByCell>
        </ByCellGroup>

        <ByCellGroup className="mx-3">
          {list.map((item, index) => (
            <ByCell
              next
              align="right"
              border={index != 0}
              key={item.quesNaireId}
              label={item.quesNaireName}
              onClick={() => setIndex(index)}
            >
              {statistic[index].unpass > 0 && (
                <ByText type="error" size="sm">
                  不合格: {statistic[index].unpass}项
                </ByText>
              )}
            </ByCell>
          ))}
        </ByCellGroup>
      </Page>

      <PageContainer round show={showPopup} onAfterLeave={() => setIndex(-1)}>
        {showPopup && (
          <PopupStandardContent
            title={modifyData.quesNaireName}
            list={modifyData.quesNaireContent}
            onConfirm={handleChange}
            onCancel={() => setIndex(-1)}
          />
        )}
      </PageContainer>
    </>
  );
};
